@(issue: Option[gitbucket.core.model.Issue],
  comments: List[gitbucket.core.model.Comment],
  hasWritePermission: Boolean,
  repository: gitbucket.core.service.RepositoryService.RepositoryInfo,
  pullreq: Option[gitbucket.core.model.PullRequest] = None)(implicit context: gitbucket.core.controller.Context)
@import gitbucket.core.view.helpers
@import gitbucket.core.model.CommitComment
@if(issue.isDefined){
  <div class="issue-avatar-image">@helpers.avatarLink(issue.get.openedUserName, 48)</div>
  <div class="panel panel-default issue-comment-box">
    <div class="panel-heading">
      @helpers.user(issue.get.openedUserName, styleClass="username strong") <span class="muted">commented @gitbucket.core.helper.html.datetimeago(issue.get.registeredDate)</span>
      <span class="pull-right">
        @if(hasWritePermission || context.loginAccount.map(_.userName == issue.get.openedUserName).getOrElse(false)){
          <a href="#" data-issue-id="@issue.get.issueId"><i class="octicon octicon-pencil" aria-label="Edit"></i></a>
        }
      </span>
    </div>
    <div class="panel-body issue-content markdown-body" id="issueContent">
      @helpers.markdown(
        markdown = issue.get.content getOrElse "No description provided.",
        repository = repository,
        enableWikiLink = false,
        enableRefsLink = true,
        enableLineBreaks = true,
        enableTaskList = true,
        hasWritePermission = hasWritePermission
      )
    </div>
  </div>
}
@issueOrPullRequest()={ @if(issue.isDefined && issue.get.isPullRequest)( "pull request" )else( "issue" ) }

@comments.map {
  case comment: gitbucket.core.model.IssueComment => {
    @if(comment.action != "close" && comment.action != "reopen" && comment.action != "delete_branch"
      && comment.action != "commit" && comment.action != "refer"){
      <div class="issue-avatar-image">@helpers.avatarLink(comment.commentedUserName, 48)</div>
      <div class="panel panel-default issue-comment-box" id="comment-@comment.commentId">
        <div class="panel-heading">
          @helpers.user(comment.commentedUserName, styleClass="username strong")
          <span class="muted">
            @if(comment.action == "comment"){
              commented
            } else {
              referenced the @issueOrPullRequest()
            }
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </span>
          @if(comment.action != "commit" && comment.action != "merge" && comment.action != "refer"
                && (hasWritePermission || context.loginAccount.map(_.userName == comment.commentedUserName).getOrElse(false))){
            <span class="pull-right">
              <a href="#" data-comment-id="@comment.commentId"><i class="octicon octicon-pencil" aria-label="Edit"></i></a>&nbsp;
              <a href="#" data-comment-id="@comment.commentId"><i class="octicon octicon-x" aria-label="Remove"></i></a>
            </span>
          }
          </div>
        <div class="panel-body issue-content markdown-body" id="commentContent-@comment.commentId">
          @helpers.markdown(
            markdown = comment.content,
            repository = repository,
            enableWikiLink = false,
            enableRefsLink = true,
            enableLineBreaks = true,
            enableTaskList = true,
            hasWritePermission = hasWritePermission
          )
        </div>
      </div>
    }
    @if(comment.action == "commit"){
      @defining({
        val (content, id) = " ([a-f0-9]{40})$".r.findFirstMatchIn(comment.content)
          .map(m => (m.before.toString -> Some(m.group(1))))
          .getOrElse(comment.content -> None)
        val head = content.take(100).takeWhile(_ != '\n')
        (id, head, if(head == content){ None }else{ Some(content.drop(head.length).dropWhile(_ == '\n')) }.filter(_.nonEmpty))
      }){ case (commitId, head, rest) =>
        <div class="discussion-item discussion-item-commit">
          <div class="discussion-item-header">
            <span class="discussion-item-icon"><i class="octicon octicon-bookmark"></i></span>
            @helpers.avatar(comment.commentedUserName, 16)
            @helpers.user(comment.commentedUserName, styleClass="username strong")
            added a commit that referenced this @issueOrPullRequest()
            @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
          </div>
          <div style="discussion-item-content">
            @commitId.map{ id =>
              <span class="pull-right"><a href="@context.path/@repository.owner/@repository.name/commit/@id" class="monospace">@id.substring(0, 7)</a></span>
            }
            <span class="discussion-item-content-head"><i class="octicon octicon-git-commit"></i></span>
            @helpers.link(head, repository)
            @rest.map{ content =>
              <a href="javascript:void(0)" class="omit" onclick="$(this.parentNode).find('.discussion-item-content-text').toggle()">...</a>
              <pre class="reset discussion-item-content-text" style="display:none">@helpers.link(content, repository)</pre>
            }
          </div>
        </div>
      }
    }
    @if(comment.action == "refer"){
      <div class="discussion-item discussion-item-refer">
        <div class="discussion-item-header">
          <span class="discussion-item-icon"><i class="octicon octicon-bookmark"></i></span>
          @helpers.avatar(comment.commentedUserName, 16)
          @helpers.user(comment.commentedUserName, styleClass="username strong")
          referenced the @issueOrPullRequest()
          @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
        </div>
        <div style="discussion-item-content">
          @defining(comment.content.split(":")){ case Array(issueId, rest @ _*) =>
            <strong>@helpers.issueLink(repository, issueId.toInt): @rest.mkString(":")</strong>
          }
        </div>
      </div>
    }
    @if(comment.action == "merge"){
      <div class="discussion-item discussion-item-merge">
        <div class="discussion-item-header">
          <span class="discussion-item-icon"><i class="octicon octicon-git-merge"></i></span>
          @helpers.avatar(comment.commentedUserName, 16)
          @helpers.user(comment.commentedUserName, styleClass="username strong")
          merged commit
          <code>@pullreq.map(_.commitIdTo.substring(0, 7))</code> into
          @if(pullreq.get.requestUserName == repository.owner){
            <code>@pullreq.map(_.branch)</code> from <code>@pullreq.map(_.requestBranch)</code>
          } else {
            <code>@pullreq.map(_.userName):@pullreq.map(_.branch)</code> from <code>@pullreq.map(_.requestUserName):@pullreq.map(_.requestBranch)</code>
          }
          @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
        </div>
      </div>
    }
    @if(comment.action == "close" || comment.action == "close_comment"){
      <div class="discussion-item discussion-item-close">
        <div class="discussion-item-header">
          <span class="discussion-item-icon"><i class="octicon octicon-circle-slash"></i></span>
          @helpers.avatar(comment.commentedUserName, 16)
          @helpers.user(comment.commentedUserName, styleClass="username strong")
          closed this @issueOrPullRequest()
          @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
        </div>
      </div>
    }
    @if(comment.action == "reopen" || comment.action == "reopen_comment"){
      <div class="discussion-item discussion-item-reopen">
        <div class="discussion-item-header">
          <span class="discussion-item-icon"><i class="octicon octicon-primitive-dot"></i></span>
          @helpers.avatar(comment.commentedUserName, 16)
          @helpers.user(comment.commentedUserName, styleClass="username strong")
          reopened the @issueOrPullRequest()
          @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
        </div>
      </div>
    }
    @if(comment.action == "delete_branch"){
      <div class="discussion-item discussion-item-delete_branch">
        <div class="discussion-item-header">
          <span class="discussion-item-icon"><i class="octicon octicon-git-branch"></i></span>
          @helpers.avatar(comment.commentedUserName, 16)
          @helpers.user(comment.commentedUserName, styleClass="username strong")
          deleted the <code>@pullreq.map(_.requestBranch)</code> branch
          @gitbucket.core.helper.html.datetimeago(comment.registeredDate)
        </div>
      </div>
    }
  }
  case comment: CommitComment => {
    @gitbucket.core.helper.html.commitcomment(comment, hasWritePermission, repository, pullreq.map(_.commitIdTo))
  }
}
<script>
$(function(){
@if(issue.isDefined){
  $('.issue-comment-box i.octicon-pencil').click(function(){
    var id  = $(this).closest('a').data('comment-id');
    var url = '@helpers.url(repository)/issue_comments/_data/' + id;
    var $content = $('#commentContent-' + id);

    if(!id){
      id  = $(this).closest('a').data('issue-id');
      url = '@helpers.url(repository)/issues/_data/' + id;
      $content = $('#issueContent');
    }

    $.get(url,
    {
      dataType : 'html'
    },
    function(data){
      $content.empty().html(data);
    });
    return false;
  });
  $('.issue-comment-box i.octicon-x').click(function(){
    if(confirm('Are you sure you want to delete this?')) {
      var id = $(this).closest('a').data('comment-id');
      $.post('@helpers.url(repository)/issue_comments/delete/' + id,
      function(data){
        if(data > 0) {
          $('#comment-' + id).prev('div.issue-avatar-image').remove();
          $('#comment-' + id).remove();
        }
      });
    }
    return false;
  });
}
  $(document).on('click', '.commit-comment-box i.octicon-pencil', function(){
    var id  = $(this).closest('a').data('comment-id');
    var url = '@helpers.url(repository)/commit_comments/_data/' + id;
    var $content = $('.commit-commentContent-' + id, $(this).closest('.commit-comment-box'));

    $.get(url,
    {
      dataType : 'html'
    },
    function(data){
      $content.empty().html(data);
    });
    return false;
  });
  $(document).on('click', '.commit-comment-box i.octicon-x', function(){
    if(confirm('Are you sure you want to delete this?')) {
      var id = $(this).closest('a').data('comment-id');
      $.post('@helpers.url(repository)/commit_comments/delete/' + id,
      function(data){
        if(data > 0) {
          $('.commit-comment-' + id).closest('.not-diff').remove();
          $('.commit-comment-' + id).closest('.inline-comment').remove();
        }
      });
    }
    return false;
  });

  var extractMarkdown = function(data){
    $('body').append('<div id="tmp"></div>');
    $('#tmp').html(data);
    var markdown = $('#tmp textarea').val();
    $('#tmp').remove();
    return markdown;
  };

  var replaceTaskList = function(issueContentHtml, checkboxes) {
    var ss = [],
        markdown = extractMarkdown(issueContentHtml),
        xs = markdown.split(/- \[[x| ]\]/g);
    for (var i=0; i<xs.length; i++) {
      ss.push(xs[i]);
      if (checkboxes.eq(i).prop('checked')) ss.push('- [x]');
      else ss.push('- [ ]');
    }
    ss.pop();
    return ss.join('');
  };

  $('div[class*=commit-commentContent-]').on('click', ':checkbox', function(ev){
    var $commentContent = $(ev.target).parents('div[class*=commit-commentContent-]'),
        commentId = $commentContent.attr('class').match(/commit-commentContent-.+/)[0].replace(/commit-commentContent-/, ''),
        checkboxes = $commentContent.find(':checkbox');
    $.get('@helpers.url(repository)/commit_comments/_data/' + commentId,
      {
        dataType : 'html'
      },
      function(responseContent){
        $.ajax({
          url: '@helpers.url(repository)/commit_comments/edit/' + commentId,
          type: 'POST',
          data: {
            issueId : 0,
            content : replaceTaskList(responseContent, checkboxes)
          },
          success: function(data) {
            $('.commit-commentContent-' + commentId).html(data.content);
          }
        });
      }
    );
  });

  @if(issue.isDefined){
  $('#issueContent').on('click', ':checkbox', function(ev){
    var checkboxes = $('#issueContent :checkbox');
    $.get('@helpers.url(repository)/issues/_data/@issue.get.issueId',
      {
        dataType : 'html'
      },
      function(responseContent){
        $.ajax({
          url: '@helpers.url(repository)/issues/edit/@issue.get.issueId',
          type: 'POST',
          data: {
            title   : $('#issueTitle').text(),
            content : replaceTaskList(responseContent, checkboxes)
          }
        });
      }
    );
  });

  $('div[id^=commentContent-]').on('click', ':checkbox', function(ev){
    var $commentContent = $(ev.target).parents('div[id^=commentContent-]'),
        commentId = $commentContent.attr('id').replace(/commentContent-/, ''),
        checkboxes = $commentContent.find(':checkbox');
    $.get('@helpers.url(repository)/issue_comments/_data/' + commentId,
      {
        dataType : 'html'
      },
      function(responseContent){
        $.ajax({
          url: '@helpers.url(repository)/issue_comments/edit/' + commentId,
          type: 'POST',
          data: {
            issueId : 0,
            content : replaceTaskList(responseContent, checkboxes)
          }
        });
      }
    );
  });

  }

});
</script>
